package biznussoft.metercor.fragments;

import java.util.HashMap;

import android.app.Activity;
import android.os.Bundle;
import android.support.v4.view.MenuItemCompat;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.Spinner;
import android.widget.TextView;
import biznussoft.metercor.HomeActivity;
import biznussoft.metercor.R;
import biznussoft.metercor.listeners.DialogListener;
import biznussoft.metercor.listeners.GlobalListener;
import biznussoft.metercor.model.Bean_Class;
import biznussoft.metercor.model.TimeModel;
import biznussoft.metercor.utils.Session;

import com.salesforce.androidsdk.app.SalesforceSDKManager;
import com.salesforce.androidsdk.rest.RestClient;
import com.salesforce.androidsdk.rest.RestClient.AsyncRequestCallback;
import com.salesforce.androidsdk.rest.RestRequest;
import com.salesforce.androidsdk.rest.RestResponse;
import com.salesforce.androidsdk.util.EventsObservable;
import com.salesforce.androidsdk.util.EventsObservable.EventType;

public class TimeFragment extends BaseFragment implements OnClickListener{
	LinearLayout viewMode,editMode;
	private RestClient client;
	private TextView tvSno,tvActivity,tvType,tvTechnician,tvStartDate,tvEndDate,tvDuration,tvCost,tvComments,tvEditTechnician,tvEditActivity;
	private EditText etStartDate,etEndDate,etComments;
	private Spinner spType;
	private CheckBox cbBillable,cdEditBillable;                    
	private Button save;
	private DialogListener dialoglistener;  
	private TimeModel model;
	private GlobalListener mHomeItemListener;   
	private String id; 
	@Override
	public void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		setHasOptionsMenu(true);
	}


	@Override
	public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {

		MenuItem addContact = menu.add("Edit");
		MenuItemCompat.setShowAsAction(addContact, MenuItemCompat.SHOW_AS_ACTION_ALWAYS | MenuItemCompat.SHOW_AS_ACTION_WITH_TEXT);
		addContact.setIcon(R.drawable.edit); 
		MenuItem actionItem = menu.add("Logout");                 
		MenuItemCompat.setShowAsAction(actionItem,MenuItemCompat.SHOW_AS_ACTION_ALWAYS | MenuItemCompat.SHOW_AS_ACTION_WITH_TEXT);
		actionItem.setIcon(R.drawable.logout); 
		super.onCreateOptionsMenu(menu, inflater);
	}


	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		if(item.getTitle().equals("Logout")){
			SalesforceSDKManager.getInstance().logout(getActivity());}
		
		if(item.getTitle().equals("Edit")){
			viewMode.setVisibility(View.GONE);
			editMode.setVisibility(View.VISIBLE);
			if(cbBillable.isChecked()){
				cdEditBillable.setChecked(true);
			}
			else{
				cdEditBillable.setChecked(false);
			}
			tvEditActivity.setText(model.getActivity());
			tvEditTechnician.setText(model.getTechnician());
			etStartDate.setText(model.getStartDate());
			etEndDate.setText(model.getEndDate());
			etComments.setText(model.getComments());
		}
		return super.onOptionsItemSelected(item);
	}

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		return inflater.inflate(R.layout.time_details_fragment, null);
	}
	@Override
	public void onAttach(Activity activity) {
		// TODO Auto-generated method stub
		super.onAttach(activity);
		dialoglistener = (DialogListener) getActivity();
		mHomeItemListener = (GlobalListener) getActivity();
	}

	@Override
	public void onActivityCreated(Bundle savedInstanceState) {
		super.onActivityCreated(savedInstanceState);

		client =  HomeActivity.mActivity.client;
		etStartDate = (EditText) getView().findViewById(R.id.etStartDate);
		etEndDate = (EditText) getView().findViewById(R.id.etEndDate);
		etStartDate.setOnClickListener(this);
		etEndDate.setOnClickListener(this);
		etComments = (EditText) getView().findViewById(R.id.etComments);


		save = (Button) getView().findViewById(R.id.save);
		save.setOnClickListener(this);
		viewMode = (LinearLayout) getView().findViewById(R.id.lllayouttimeViewMode);
		editMode = (LinearLayout) getView().findViewById(R.id.lllayouttimeEditMode);
		spType = (Spinner) getView().findViewById(R.id.spType);
		tvSno = (TextView) getView().findViewById(R.id.tvSno);
		tvActivity = (TextView) getView().findViewById(R.id.tvActivity);
		tvEditActivity = (TextView) getView().findViewById(R.id.tveditActivity);
		tvEditTechnician = (TextView) getView().findViewById(R.id.tvedittechnician);
		tvType = (TextView) getView().findViewById(R.id.tvType);
		tvTechnician = (TextView) getView().findViewById(R.id.tvtechnician);
		tvStartDate = (TextView) getView().findViewById(R.id.tvStartDate);
		tvEndDate = (TextView) getView().findViewById(R.id.tvEndDate);
		tvDuration = (TextView) getView().findViewById(R.id.tvDuration);
		tvCost = (TextView) getView().findViewById(R.id.tvCost);
		tvComments = (TextView) getView().findViewById(R.id.tvComments);
		cbBillable = (CheckBox) getView().findViewById(R.id.tvBillable);
		cdEditBillable = (CheckBox) getView().findViewById(R.id.editCheckBillable);

	}


	public void showRecords(int position){
		model =TimeMasterFragment.timeList.get(position);
		tvActivity.setText(model.getActivityName());
		tvType.setText(model.getType());
		tvTechnician.setText(model.getTechnician());
		tvStartDate.setText(model.getStartDate());
		tvEndDate.setText(model.getEndDate());
		tvDuration.setText(model.getDuration());
		tvCost.setText(model.getCost());
		tvComments.setText(model.getComments());
		if(model.isBillable()){
			cbBillable.setChecked(true);
		}else{
			cbBillable.setChecked(false);
		}
		
		id = model.getId();
	}

	@Override
	public void onClick(View v) {
		switch (v.getId()) {

		case R.id.save:
			updateTime(id);
			break;
		case R.id.etStartDate:
			Session.sStartTime = true;
			Session.sEndTime = false;
			Session.sActivity = false;
			Session.sTime = true;
			Session.sExpense = false;
			Session.sNewTime = false;
			Session.sNewExpenses = false;
			dialoglistener.nextDialog("date");
			break;
		case R.id.etEndDate:
			Session.sStartTime = false;
			Session.sEndTime = true;
			Session.sActivity = false;
			Session.sTime = true;
			Session.sExpense = false;
			Session.sNewTime = false;
			Session.sNewExpenses = false;
			dialoglistener.nextDialog("date");
			break;

		default:
			break;
		}
	}

	public void setStartDate(String date){

		etStartDate.setText(date);
	}
	public void setEndDate(String date){

		etEndDate.setText(date);               

	}

	private void updateTime(String id){
		
		boolean flag = cdEditBillable.isChecked();

		String objectType = "FConnect__Time__c";                                 
		HashMap<String, Object> fields = new HashMap<String, Object>();
		fields.put("Start_Date_Time__c",etStartDate.getText().toString());
		fields.put("End_Date_Time__c",etEndDate.getText().toString());
		fields.put("FConnect__Comments__c",etComments.getText().toString());
		fields.put("FConnect__Type__c",spType.getSelectedItem().toString());
		fields.put("FConnect__Billable__c",flag);
		try {
			
			RestRequest restRequest = RestRequest.getRequestForUpdate(Bean_Class.api_Version,objectType,id,fields);
			Log.i("NCS","Request 2 is   :"+restRequest);

			client.sendAsync(restRequest, new AsyncRequestCallback() {
				@Override
				public void onSuccess(RestRequest request, RestResponse result) {
					try {     
						 
						finishFragment();
					}                                                
					catch (Exception e) {
						Log.i("TPT","Exception is   :"+e.getMessage());                      
					}
				}

				//@Override
				public void onError(Exception exception) {

					EventsObservable.get().notifyEvent(EventType.RenditionComplete);
				}
			});
		} 
		catch (Exception e) {
			Log.i("NCS","Exception is   :"+e.getMessage());

		}

	}
	
	public void finishFragment(){
		getActivity().getSupportFragmentManager().beginTransaction().remove(this).commit();
	}


}
